package java;

public class Question32 {
    public static void main(String[] args) {
        System.out.println(longestValidParentheses(")()()())())(()())())(())()"));
    }
    public static int longestValidParentheses(String s) {
        if (s == null || s.length() < 1) {
            return 0;
        }
        int res = 0;
        int left = 0;
        while (left < s.length()){
            if (s.charAt(left) == '('){
                int leftBracketNum = 0;
                int rightBracketNum = 0;
                for (int i = left; i < s.length();i ++){
                    if (s.charAt(i) == '('){
                        leftBracketNum ++;
                    }else {
                        rightBracketNum ++;
                    }
                    if (rightBracketNum > leftBracketNum){
                        if (i - left > res){
                            res = i - left;
                        }
                        break;
                    }
                    if (rightBracketNum == leftBracketNum){
                        if (i - left > res){
                            res = i - left + 1;
                        }
                    }
                }
                if (leftBracketNum == rightBracketNum){
                    left = left + res + 1;
                }
            }
            left ++;
        }

        return res;
    }
}
